//TODO 获取图书基本信息 --邹光山 
const connectiondb = require("../sql/mysql")
/* 
    TODO 删除图书信息
*/
async function del(req, res) {
    const {book_id} = req.body;
    const sql = "delete from book_info where book_id = ?"
    await connectiondb(sql, [book_id])
    res.send({ code: 200, msg: '删除图书成功' })
}
/* 
    TODO 获取所有的图书信息 --邹光山
*/
async function queryAll(req, res) {
    const result = await connectiondb("select * from book_info", [])
    res.send({ code: 200, msg: "获取图书信息成功", data: result })
}

/* 
    TODO 添加图书信息 --邹光山
*/
async function add(req, res) {
    const { name, author, publish, introduction,language,price,pubdate} = req.body;
    const sql = "insert into book_info value(null,?,?,?,?,?,?,?,?,?,?)";
    const ISBN=Math.floor(Math.random()*100+1)
    const cid=Math.floor(Math.random()*10+1)
    const stock=Math.floor(Math.random()*10+1)
    await connectiondb(sql, [name, author, publish, ISBN, introduction,language,price,pubdate,cid, stock])
    res.send({ code: 200, msg: "添加图书信息成功" })
}

/* 
    TODO 根据book_id查询图书信息  --邹光山
*/
async function queryOne(req, res) {
    const { book_id} = req.body;
    const sql = "select * from book_info where book_id= ?"
    const result = await connectiondb(sql, [book_id])
    res.send({ code: 200, msg: "根据book_id获取图书信息成", data: result[0] })
}

/* 
    TODO 修改图书信息 --邹光山
*/
async function update(req, res) {
    const { book_id, name, author, publish, introduction,language,price,pubdate} = req.body;
    console.log(book_id, name, author, publish, introduction,language,price,pubdate);
    const sql = "update book_info set name = ? , author = ? ,publish= ? , ISBN = ? , introduction = ? , language = ?,price= ? ,pubdate=?,cid=?,stock=? where book_id = ?"
    const ISBN=Math.floor(Math.random()*100+1)
    const cid=Math.floor(Math.random()*10+1)
    const stock=Math.floor(Math.random()*10+1)
    await connectiondb(sql, [  name, author, publish, ISBN, introduction,language,price,pubdate,cid, stock,book_id])
    res.send({code:200,msg:"修改图书信息成功"})
}


/* 
    TODO 根据图书名进行模糊查询 --邹光山
*/
async function likename(req,res){
    const name = req.body;
   const name1=name.searchName;
    console.log(name1);
    const sql = `select * from book_info where name like '%${name1}%'`;
    const result = await connectiondb(sql,[])
    res.send({code:200,msg:"模糊查询成功",data:result})
    console.log(result);
}

/* 
    TODO 根据cid获取图书信息 --邹光山
*/
async function queryByCid(req,res){
    const {cid} = req.body;
    const sql = "select * from book_info where cid = ?"
    const result = await connectiondb(sql,[cid])
    res.send({code:200,msg:"根据cid获取分类图书信息",data:result})
}
module.exports = {
    del,
    queryAll,
    add,
    queryOne,
    update,
    likename,
    queryByCid
}